package com.lakeworks.common.utils.uuid;

import io.netty.util.internal.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * ID生成器工具类
 *
 * @author lakeworks
 */
@Component
public class IdUtils {


    private static RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    public IdUtils(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    /**
     * 获取随机UUID
     *
     * @return 随机UUID
     */
    public static String randomUUID() {
        return UUID.randomUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线
     *
     * @return 简化的UUID，去掉了横线
     */
    public static String simpleUUID() {
        return UUID.randomUUID().toString(true);
    }

    /**
     * 获取随机UUID，使用性能更好的ThreadLocalRandom生成UUID
     *
     * @return 随机UUID
     */
    public static String fastUUID() {
        return UUID.fastUUID().toString();
    }

    /**
     * 简化的UUID，去掉了横线，使用性能更好的ThreadLocalRandom生成UUID
     *
     * @return 简化的UUID，去掉了横线
     */
    public static String fastSimpleUUID() {
        return UUID.fastUUID().toString(true);
    }


    //redis自增序列
    public static String SeqGenerator(String prefix, int numLength) {
        String upperCode = "";
        Long size = redisTemplate.opsForList().size(prefix);
        if (size > 0) {
            List leve = redisTemplate.opsForList().range(prefix, 0, -1);
            upperCode = leve.get(leve.size() - 1).toString();
        }
        String returnCode = "";
        int Suffix;
        if (!StringUtil.isNullOrEmpty(upperCode)) {
            String sequence = upperCode.substring(prefix.length());
            Suffix = Integer.parseInt(sequence);
            Suffix++;
        } else {
            Suffix = 1;
        }
        returnCode = prefix + String.format("%0" + numLength + "d", Suffix);
        redisTemplate.opsForList().rightPush(prefix, returnCode);
        return returnCode;
    }


}
